package com.tepth.remote.control.delegate.file;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.AppCompatTextView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.blankj.utilcode.util.ToastUtils;
import com.liulishuo.filedownloader.BaseDownloadTask;
import com.liulishuo.filedownloader.FileDownloadListener;
import com.liulishuo.filedownloader.FileDownloader;
import com.tepth.remote.control.R;
import com.tepth.remote.control.R2;
import com.tepth.remote.control.base.bean.FileBean;
import com.tepth.remote.control.base.config.ApiDictionary;
import com.tepth.remote.control.base.refresh.RefreshCallback;
import com.tepth.remote.control.base.refresh.RefreshHandler;
import com.tepth.remote.control.delegate.BasePermissionCheckerDelegate;
import com.tepth.remote.core.app.Control;
import com.tepth.remote.core.net.CommonParams;
import com.tepth.remote.core.utils.file.FileUtil;
import com.tepth.remote.core.utils.file.OpenFileHandler;
import com.tepth.remote.ui.alert.DialogLoader;
import com.tepth.remote.ui.alert.IDialogClickListener;
import com.tepth.remote.ui.recycler.ItemType;
import com.tepth.remote.ui.recycler.MultipleFields;
import com.tepth.remote.ui.recycler.MultipleItemEntity;
import com.tepth.remote.ui.recycler.MultipleRecyclerAdapter;
import com.tepth.remote.ui.recycler.MultipleRecyclerClickListener;
import com.tepth.remote.ui.recycler.grid.GridItemType;
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Description:
 *
 * @author Hequn.Lee
 * @date 2018/11/23
 */
public class FileDelegate extends BasePermissionCheckerDelegate implements MultipleRecyclerClickListener, RefreshCallback {

    @BindView(R2.id.icon_toolbar_title)
    AppCompatTextView toolbarTitle = null;
    @BindView(R2.id.multiple_recyclerView)
    RecyclerView mRecyclerView = null;
    @BindView(R2.id.multiple_swipeRefresh)
    SwipeRefreshLayout mSwipeRefreshLayout = null;
    private RefreshHandler mRefreshHandler = null;
    private DialogLoader mDialogLoader = null;
    private MultipleRecyclerAdapter mAdapter = null;

    @OnClick(R2.id.icon_toolbar_back)
    void onBack() {
        pop();
    }

    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        super.onLazyInitView(savedInstanceState);
        toolbarTitle.setText("文件资源管理");
    }

    private void initRecyclerView() {
        mDialogLoader = new DialogLoader(getProxyActivity());
        final LinearLayoutManager manager = new LinearLayoutManager(getProxyActivity());
        mRecyclerView.setLayoutManager(manager);
        mRecyclerView.addItemDecoration(new HorizontalDividerItemDecoration
                .Builder(getProxyActivity())
                .color(R.color.font_gray_light)
                .size(1)
                .build());
    }

    @Override
    public Object setLayout() {
        return R.layout.delegate_multiple_list;
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, View rootView) {
        readStorageWithCode();
        initRecyclerView();
        FileDownloader.setup(getProxyActivity());
        mDialogLoader.showProgressDialog(false, "正在加载...", "");
        mRefreshHandler = RefreshHandler.create(mSwipeRefreshLayout,
                mRecyclerView, new FileDataConvert(),
                ApiDictionary.API_FILE_LIST, this,
                CommonParams.SUCCESS_CODE_ZERO, 2);
        mRefreshHandler.firstLoadData(this);
    }

    @Override
    public void onclickListener(MultipleFields type, int id) {
        if (mAdapter == null) {
            mAdapter = mRefreshHandler.getAdapter();
        }
        final List<MultipleItemEntity> arrayList = mAdapter.getData();
        FileBean result = null;
        MultipleItemEntity entity = null;
        int position = -1;
        final int size = arrayList.size();
        for (int i = 0; i < size; i++) {
            final FileBean bean = arrayList.get(i).getField(type);
            if (id == bean.getId()) {
                result = bean;
                entity = arrayList.get(i);
                position = i;
                break;
            }
        }
        if (entity != null) {
            final int status = entity.getField(MultipleFields.TAG);
            final String filePath = FileUtil.getDirPath("Tepth") + "/"
                    + result.getName()
                    + result.getUrl().substring(
                    result.getUrl()
                            .lastIndexOf("."),
                    result.getUrl()
                            .length());
            if (status == ItemType.FILE_NOT_FOUND) {
                FileDownloader.getImpl().create(result.getUrl())
                        .setPath(filePath, false)
                        .setCallbackProgressTimes(300)
                        .setMinIntervalUpdateSpeed(400)
                        .setListener(createDownloadListener(position, entity))
                        .start();
            } else if (status == ItemType.FILE_COMPLETE) {
                try {
                    Intent intent = OpenFileHandler.openFile(filePath);
                    // 打开文件
                    Control.getApplicationContext().startActivity(intent);
                } catch (Exception e) {
                    e.printStackTrace();
                    ToastUtils.showShort(
                            "无法打开该文件!请在：/sdcard/Tepth"
                                    + "/"
                                    + result.getName()
                                    + result.getUrl().substring(
                                    result.getUrl()
                                            .lastIndexOf("."),
                                    result.getUrl()
                                            .length())
                                    + "路径下查看");
                }
            }
        }
    }

    @Override
    public void onLoadRecyclerError(String msg) {
        mDialogLoader.showFailed("加载失败", "", new IDialogClickListener() {
                    @Override
                    public void onClick() {
                        mDialogLoader.clearDialog();
                        mRefreshHandler.requestRetrofitData(false, FileDelegate.this);
                    }
                },
                new IDialogClickListener() {
                    @Override
                    public void onClick() {
                        pop();
                        mDialogLoader.clearDialog();
                    }
                });
    }

    @Override
    public void onclickViewPagerListener(GridItemType type) {
    }

    private FileDownloadListener createDownloadListener(final int position, final MultipleItemEntity entity) {
        if (mAdapter == null) {
            mAdapter = mRefreshHandler.getAdapter();
        }
        return new FileDownloadListener() {
            @Override
            protected void pending(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                entity.setField(MultipleFields.TAG, ItemType.FILE_DOWNING);
                mAdapter.setData(position, entity);
            }

            @Override
            protected void progress(BaseDownloadTask task, int soFarBytes, int totalBytes) {

            }

            @Override
            protected void completed(BaseDownloadTask task) {
                entity.setField(MultipleFields.TAG, ItemType.FILE_COMPLETE);
                mAdapter.setData(position, entity);
            }

            @Override
            protected void paused(BaseDownloadTask task, int soFarBytes, int totalBytes) {

            }

            @Override
            protected void error(BaseDownloadTask task, Throwable e) {
                entity.setField(MultipleFields.TAG, ItemType.FILE_NOT_FOUND);
                mAdapter.setData(position, entity);
                ToastUtils.showShort("下载失败，无法下载该文件");
            }

            @Override
            protected void warn(BaseDownloadTask task) {

            }
        };
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @Override
    public void onRefreshCallback() {
        mDialogLoader.clearDialog();
    }
}
